import glob
import os
import re
from reportlab.pdfgen import canvas
from reportlab.pdfbase import ttfonts, pdfmetrics
from reportlab.lib.pagesizes import letter

def draw_poem_on_canvas(c, text_file, font_name):
    """Draws a single poem on the given canvas, then creates a new page."""
    with open(text_file, 'r', encoding='utf-8') as f:
        all_lines = f.read().strip().split('\n')

    title = all_lines[0].strip() if all_lines else ""
    author = all_lines[1].strip() if len(all_lines) > 1 else ""
    body_content = '\n'.join(all_lines[2:]) if len(all_lines) > 2 else '\n'.join(all_lines)

    body_lines = re.split(r'[，。！？\n]', body_content)
    processed_body_lines = [line.strip() for line in body_lines if line.strip()]

    if not processed_body_lines:
        print(f"Skipping file with no content: {text_file}")
        return

    width, height = letter
    margin = 40

    title_font_size = 36
    author_font_size = 24
    body_font_size = 120  # Starting size for the body
    line_spacing_ratio = 1.5

    # Calculate optimal body font size
    while body_font_size > 6:
        c.setFont(font_name, body_font_size)
        body_line_height = body_font_size * line_spacing_ratio
        max_line_width = max(c.stringWidth(line, font_name, body_font_size) for line in processed_body_lines)

        title_height = title_font_size * 1.2
        author_height = author_font_size * 1.2
        body_height = len(processed_body_lines) * body_line_height
        total_content_height = title_height + author_height + body_height

        if max_line_width < (width - 2 * margin) and total_content_height < (height - 2 * margin):
            break
        body_font_size -= 2

    # Draw content
    body_line_height = body_font_size * line_spacing_ratio
    title_height = title_font_size * 1.2
    author_height = author_font_size * 1.2
    body_height = (len(processed_body_lines) - 1) * body_line_height
    total_height = title_height + author_height + body_height

    y = (height + total_height) / 2

    # Draw Title
    c.setFont(font_name, title_font_size)
    text_width = c.stringWidth(title, font_name, title_font_size)
    x = (width - text_width) / 2
    c.drawString(x, y, title)
    y -= title_height

    # Draw Author
    c.setFont(font_name, author_font_size)
    text_width = c.stringWidth(author, font_name, author_font_size)
    x = (width - text_width) / 2
    c.drawString(x, y, author)
    y -= author_height * 1.5  # Add extra space after author

    # Draw Body
    c.setFont(font_name, body_font_size)
    for line in processed_body_lines:
        text_width = c.stringWidth(line, font_name, body_font_size)
        x = (width - text_width) / 2
        c.drawString(x, y, line)
        y -= body_line_height

    c.showPage() # Create a new page for the next poem

def main():
    output_dir = "pdf_output"
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    else:
        for f in glob.glob(os.path.join(output_dir, '*.pdf')):
            os.remove(f)

    output_pdf_path = os.path.join(output_dir, "唐诗三百首.pdf")
    c = canvas.Canvas(output_pdf_path, pagesize=letter)

    font_path = "C:/Windows/Fonts/simsun.ttc"
    font_name = 'SimSun'
    if os.path.exists(font_path):
        pdfmetrics.registerFont(ttfonts.TTFont(font_name, font_path))
    else:
        font_name = "Helvetica"

    files = glob.glob(os.path.join("唐诗三百首", '*.txt'))

    if not files:
        print("No text files found in the '唐诗三百首' directory.")
        return

    print(f"Found {len(files)} poems. Combining them into a single PDF...")

    for text_file in sorted(files): # Sort files for consistent order
        try:
            draw_poem_on_canvas(c, text_file, font_name)
            print(f"Added {os.path.basename(text_file)} to the PDF.")
        except Exception as e:
            print(f"Error processing {text_file}: {e}")

    c.save()
    print(f"Successfully created {output_pdf_path}")

if __name__ == "__main__":
    main()


